package messages

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	"io"
	"net/http"
	"time"
)

// FeishuRobotSender 飞书机器人
// 详见官方文档：https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot
type FeishuRobotSender struct {
	cnf configstc.WebHookConfig

	client *http.Client
}

func NewFeishuRobotSender(cnf configstc.WebHookConfig) *FeishuRobotSender {
	client := &http.Client{
		Timeout: 3 * time.Second,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}

	return &FeishuRobotSender{
		cnf:    cnf,
		client: client,
	}
}

// SendText 发送文本
func (s *FeishuRobotSender) SendText(message string) error {
	_, err := s.OriginSend(map[string]interface{}{
		"msgtype": "text",
		"content": map[string]interface{}{
			"text": message, //内容
		},
	})
	return err
}

func (s *FeishuRobotSender) OriginSend(params map[string]interface{}) ([]byte, error) {
	reqBody, err := json.Marshal(params)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest(http.MethodPost, s.cnf.Url, bytes.NewReader(reqBody))
	if err != nil {
		return nil, err
	}
	req.Header.Add("Content-Type", "application/json")
	resp, err := s.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	return body, nil
}
